package feizhou.untils.tools.map;


import com.fasterxml.jackson.databind.JsonNode;
import feizhou.untils.tools.ClassUtil;
import feizhou.untils.tools.StringUtil;
import feizhou.untils.tools.json.JSONUtil;
import feizhou.untils.tools.json.bean.FieldMappingTree;
import feizhou.untils.tools.json.bean.JsonNodeBean;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 描述：Object to Map
 *
 * @author： feizhou
 * @date ：2018/12/21 15:39
 * @return Map
 */
public class MapUtil {
    /**
     * 获取利用反射获取类里面的值和名称,并转化为Map
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        try {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = null;
                value = field.get(obj);
                map.put(fieldName, value);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 描述：移除Map的 null key和null value
     * 使用 Iterator 本身的方法 remove() 来删除对象， Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
     *
     * @param ：[map]
     * @return void
     * @author： feizhou
     * @date ：2018/12/21 16:09
     */
    public static void removeNullEntry(Map map) {
        if (map != null) {
            Set set = map.keySet();
            for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                Object obj = (Object) iterator.next();
                if (StringUtil.isEmpty(obj)) {
                    iterator.remove();
                    continue;
                }
                Object value = (Object) map.get(obj);
                if (StringUtil.isEmpty(value)) {
                    iterator.remove();
                    continue;
                }
            }
        }
    }

    /**
     * 获取利用反射，将map 转换bean
     * 如果数据类似不对，会抛异常
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        T bean = null;
        try {
            bean = clazz.getDeclaredConstructor().newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                Class<?> typeClass = field.getType();
                Object value = map.get(field.getName());
                Object newValue = ClassUtil.convertValueType(value, typeClass);
                field.setAccessible(true);
                field.set(bean, newValue);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return bean;
    }

    /**
     * 将json 按照规则，转换为MAP
     *
     * @return java.util.Map
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/10/13 16:22
     */
    public static Map<String, Object> toMap(JsonNode srvJson, List<FieldMappingTree> fieldMappingTrees) {
        return JsonNodeBean.buildMap(srvJson, fieldMappingTrees);
    }


    /**
     * 如果map存在，就返回map，如果不存在就构建Map
     *
     * @param map
     * @param key
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/10/13 17:25
     */
    private static Map<String, Object> getMap(Map<String, Object> map, String key) {
        Object o = map.get(key);
        if (o != null && o instanceof Map) {
            return (Map) map.get(key);
        }
        return new HashMap<>();
    }

    /**
     * 将map 转换为list，举例如下
     * school.name=中山大学
     * school.level=211
     *
     * @param map
     * @return java.util.List<java.lang.String>
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/10/26 15:00
     */
    public static List<String> toList(Map<String, Object> map) {

        List<String> list = new ArrayList<>();
        //叶子节点的Map
        Map<String, Object> leafMap = new HashMap<>();
        buildLeafMap(leafMap, map, null);

        Set<Map.Entry<String, Object>> entries = leafMap.entrySet();
        entries.forEach(e -> {

            String key = e.getKey();
            Object value = e.getValue();
            if (value instanceof List) {
                ((List) value).forEach(v1 -> list.add(key + "=" + v1));
                return;
            }
            list.add(key + "=" + value);
        });
        return list;
    }

    /**
     * 构建叶子节点的Map
     *
     * @param map
     * @return java.lang.String
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2023/10/26 15:04
     */
    private static void buildLeafMap(Map<String, Object> leafMap, Map<String, Object> map, String prifix_key) {
        Set<Map.Entry<String, Object>> entries = map.entrySet();

        for (Map.Entry<String, Object> entry : entries) {

            String key = entry.getKey();
            //prifix_key 是null 说明该key 是第一个
            String newPrifix_key = prifix_key == null ? key : prifix_key + "." + key;
            Object value = entry.getValue();
            //不是叶子节点继续递归
            if (value instanceof Map) {
                buildLeafMap(leafMap, (Map) value, newPrifix_key);
                continue;
            }
            //是叶子节点
            leafMap.put(newPrifix_key, value);
        }
    }

    public static void main(String[] args) {
        String jsonStr = "{ \"success\": true, \"message\": \"操作成功！\", \"code\": 200, \"result\": [ { \"name\": \"通告类型\", \"code\": \"msg_category\", \"items\": [ { \"value\": \"1\", \"text\": \"通知公告\", \"description\": null, \"sortOrder\": 1, \"title\": \"通知公告\" }, { \"value\": \"2\", \"text\": \"系统消息\", \"description\": null, \"sortOrder\": 1, \"title\": \"系统消息\" } ] }, { \"name\": \"开关\", \"code\": \"is_open\", \"items\": [ { \"value\": \"Y\", \"text\": \"是\", \"description\": null, \"sortOrder\": 1, \"title\": \"是\" }, { \"value\": \"N\", \"text\": \"否\", \"description\": null, \"sortOrder\": 1, \"title\": \"否\" } ] } ], \"timestamp\": 1699498826052 }";

        JsonNode jsonNode = JSONUtil.readNode(jsonStr);


        List<FieldMappingTree> list = new ArrayList<>();
        List<FieldMappingTree> child01 = new ArrayList<>();
        List<FieldMappingTree> child011 = new ArrayList<>();

        List<FieldMappingTree> child02 = new ArrayList<>();
        List<FieldMappingTree> child021 = new ArrayList<>();
        List<FieldMappingTree> child0211 = new ArrayList<>();

//        list.add(new FieldMappingTree("success1", "success", null,null,null));
//        list.add(new FieldMappingTree("code1", "code", null,null,null));
//        list.add(new FieldMappingTree("data", "result", child01,null,null));
//        list.add(new FieldMappingTree("user", null, child02,null,null));
//
//        child01.add(new FieldMappingTree("name1", "name", null,null,null));
//        child01.add(new FieldMappingTree("code1", "code", null,null,null));
//        child01.add(new FieldMappingTree("items1", "items", child011,null,null));
//
//
//        child011.add(new FieldMappingTree("value1", "value", null,null,null));
//        child011.add(new FieldMappingTree("text1", "text", null,null,null));
//
//
//        child02.add(new FieldMappingTree("data", "result", child021,null,null));
//        child021.add(new FieldMappingTree("info", "items", child0211,null,null));
//        child0211.add(new FieldMappingTree("value", "value", null,null,null));
//        child0211.add(new FieldMappingTree("text", "text", null,null,null));

        Map<String, Object> map = toMap(jsonNode, list);
        System.out.println(JSONUtil.toJsonStr(map));

        System.out.println(toList(map));
    }

}
